﻿using System;
using System.Threading.Tasks;
using CSRedis;

namespace ESoft.Redis
{
    public class RedisService : IRedisService
    {
        public bool DeleteHash(string key, string hashField)
        {
            return RedisHelper.HDel(key, hashField) > 0;
        }

        public T Get<T>(string key)
        {
            return RedisHelper.Get<T>(key);
        }

        public async Task<T> GetAsync<T>(string key)
        {
            return await RedisHelper.GetAsync<T>(key);
        }

        public T GetHash<T>(string key, string hashField)
        {
            return RedisHelper.HGet<T>(key, hashField);
        }

        public T GetOrCreateAsync<T>(string key, int time, Func<T> increatementFunc)
        {
            return RedisHelper.CacheShell<T>(key, time, increatementFunc);
        }

        public async Task<T> GetOrCreateAsync<T>(string key, int time, Func<Task<T>> increatementFunc)
        {
            return await RedisHelper.CacheShellAsync<T>(key, time, increatementFunc);
        }

        public bool Remove(string key)
        {
            return RedisHelper.Del(key) > 0;
        }

        public void Set<T>(string key, T value)
        {
            RedisHelper.Set(key, value);
        }

        public void Set<T>(string key, T value, TimeSpan expiredTime)
        {
            RedisHelper.Set(key, value, expiredTime);
        }

        public void SetHash<T>(string key, string hashField, T hashValue)
        {
            RedisHelper.HSet(key, hashField, hashValue);
        }

        public bool SetNx(string lockKey, object value, double timeoutSpan = 0)
        {
            bool success = RedisHelper.SetNx(lockKey, value);
            if (timeoutSpan > 0)
            {
                RedisHelper.Expire(lockKey, TimeSpan.FromMilliseconds(timeoutSpan));
            }
            return success;
        }

        public void Subscribe(params (string, Action<CSRedisClient.SubscribeMessageEventArgs>)[] channels)
        {
            RedisHelper.Subscribe(channels);
        }
    }
}
